<template>
  <div class="fill-height">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <el-button
          icon
          @click="$router.go(-1)"
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
        <h1 class="page-title">
          <el-icon class="title-icon"><Cpu /></el-icon>
          执行器详情 - {{ registerKey }}
        </h1>
        <el-space>
          <el-button
            type="primary"
            @click="loadExecutorDetail"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </el-space>
      </div>
    </div>

    <div v-if="executorDetail" class="executor-detail">
      <!-- 基本信息 -->
      <el-card class="detail-card" header="基本信息">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="执行器标识">{{ executorDetail.registerKey }}</el-descriptions-item>
          <el-descriptions-item label="应用名称">{{ executorDetail.appName }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(executorDetail.status)">
              {{ executorDetail.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="健康状态">
            <el-tag :type="getHealthStatusType(executorDetail.healthStatus)">
              {{ executorDetail.healthStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后心跳时间">{{ formatDateTime(executorDetail.lastHeartbeatTime) }}</el-descriptions-item>
          <el-descriptions-item label="最后监控时间">{{ formatDateTime(executorDetail.monitorTime) }}</el-descriptions-item>
          <el-descriptions-item label="运行时长">{{ formatUptime(executorDetail.environmentData?.uptimeSeconds) }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 线程池信息 -->
      <el-card class="detail-card" header="线程池信息">
        <el-row :gutter="16">
          <el-col :span="12">
            <v-chart :option="threadPoolChartOption" style="height: 250px;" />
          </el-col>
          <el-col :span="12">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="核心线程数">{{ executorDetail.corePoolSize || 0 }}</el-descriptions-item>
              <el-descriptions-item label="最大线程数">{{ executorDetail.maximumPoolSize || 0 }}</el-descriptions-item>
              <el-descriptions-item label="当前线程数">{{ executorDetail.poolSize || 0 }}</el-descriptions-item>
              <el-descriptions-item label="活跃线程数">{{ executorDetail.activeCount || 0 }}</el-descriptions-item>
              <el-descriptions-item label="队列大小">{{ executorDetail.queueSize || 0 }}</el-descriptions-item>
              <el-descriptions-item label="队列剩余容量">{{ executorDetail.queueRemainingCapacity || 0 }}</el-descriptions-item>
              <el-descriptions-item label="运行中任务">{{ executorDetail.runningTaskCount || 0 }}</el-descriptions-item>
              <el-descriptions-item label="延迟任务">{{ executorDetail.delayTaskCount || 0 }}</el-descriptions-item>
              <el-descriptions-item label="已完成任务">{{ executorDetail.completedTaskCount || 0 }}</el-descriptions-item>
              <el-descriptions-item label="总任务数">{{ executorDetail.taskCount || 0 }}</el-descriptions-item>
              <el-descriptions-item label="平均执行时间">{{ executorDetail.averageTaskExecutionTimeMs || 0 }}ms</el-descriptions-item>
              <el-descriptions-item label="内存使用率">{{ executorDetail.memoryUsagePercent || 0 }}%</el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
        
        <!-- 内存使用详情 -->
        <el-row :gutter="16" style="margin-top: 20px;">
          <el-col :span="8">
            <div class="memory-info">
              <div class="memory-title">最大内存</div>
              <div class="memory-value">{{ executorDetail.maxMemoryMb || 0 }} MB</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="memory-info">
              <div class="memory-title">已用内存</div>
              <div class="memory-value">{{ executorDetail.usedMemoryMb || 0 }} MB</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="memory-info">
              <div class="memory-title">空闲内存</div>
              <div class="memory-value">{{ (executorDetail.maxMemoryMb || 0) - (executorDetail.usedMemoryMb || 0) }} MB</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 任务执行统计 -->
      <el-card class="detail-card" header="任务执行统计">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="stat-info">
              <div class="stat-title">已完成任务</div>
              <div class="stat-value">{{ executorDetail.threadPoolStatistics?.taskExecutionStatistics?.totalCompletedTasks || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-info">
              <div class="stat-title">失败任务</div>
              <div class="stat-value">{{ executorDetail.threadPoolStatistics?.taskExecutionStatistics?.totalFailedTasks || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-info">
              <div class="stat-title">延迟任务</div>
              <div class="stat-value">{{ executorDetail.threadPoolStatistics?.taskExecutionStatistics?.totalDelayTasks || 0 }}</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-info">
              <div class="stat-title">成功率</div>
              <div class="stat-value">{{ (executorDetail.threadPoolStatistics?.taskExecutionStatistics?.taskSuccessRate || 0).toFixed(1) }}%</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="16" style="margin-top: 16px;">
          <el-col :span="12">
            <div class="stat-info">
              <div class="stat-title">平均执行时间</div>
              <div class="stat-value">{{ (executorDetail.threadPoolStatistics?.taskExecutionStatistics?.averageTaskExecutionTime || 0).toFixed(2) }}ms</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="stat-info">
              <div class="stat-title">最近一分钟完成任务</div>
              <div class="stat-value">{{ executorDetail.completedTasksLastMinute || 0 }}</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 环境监控信息 -->
      <el-card class="detail-card" header="环境监控信息">
        <el-row :gutter="16">
          <el-col :span="8">
            <v-chart :option="cpuChartOption" style="height: 200px;" />
          </el-col>
          <el-col :span="8">
            <v-chart :option="memoryChartOption" style="height: 200px;" />
          </el-col>
          <el-col :span="8">
            <v-chart :option="heapChartOption" style="height: 200px;" />
          </el-col>
        </el-row>
        
        <el-descriptions :column="3" border style="margin-top: 20px;">
          <el-descriptions-item label="CPU使用率">{{ executorDetail.environmentData?.cpuUsagePercent || 0 }}%</el-descriptions-item>
          <el-descriptions-item label="系统内存">{{ executorDetail.environmentData?.systemMemoryUsagePercent || 0 }}%</el-descriptions-item>
          <el-descriptions-item label="JVM堆内存">{{ executorDetail.environmentData?.heapMemoryUsagePercent || 0 }}%</el-descriptions-item>
          <el-descriptions-item label="线程数">{{ executorDetail.environmentData?.threadCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="守护线程">{{ executorDetail.environmentData?.daemonThreadCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="峰值线程">{{ executorDetail.environmentData?.peakThreadCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="操作系统">{{ executorDetail.environmentData?.osName || '-' }} {{ executorDetail.environmentData?.osVersion || '' }}</el-descriptions-item>
          <el-descriptions-item label="JVM版本">{{ executorDetail.environmentData?.jvmVersion || '-' }}</el-descriptions-item>
          <el-descriptions-item label="进程ID">{{ executorDetail.environmentData?.processId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="系统负载">{{ executorDetail.environmentData?.systemLoadAverage || 0 }}</el-descriptions-item>
          <el-descriptions-item label="系统运行时长">{{ formatUptime(executorDetail.environmentData?.uptimeSeconds) }}</el-descriptions-item>
          <el-descriptions-item label="JVM运行时长">{{ formatUptime(executorDetail.environmentData?.jvmUptime ? executorDetail.environmentData.jvmUptime / 1000 : 0) }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 系统资源详情 -->
        <el-row :gutter="16" style="margin-top: 20px;">
          <el-col :span="6">
            <div class="resource-info">
              <div class="resource-title">系统总内存</div>
              <div class="resource-value">{{ executorDetail.environmentData?.totalMemoryMB || 0 }} MB</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="resource-info">
              <div class="resource-title">系统已用内存</div>
              <div class="resource-value">{{ executorDetail.environmentData?.usedMemoryMB || 0 }} MB</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="resource-info">
              <div class="resource-title">JVM最大堆内存</div>
              <div class="resource-value">{{ executorDetail.environmentData?.maxHeapMemoryMB || 0 }} MB</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="resource-info">
              <div class="resource-title">JVM已用堆内存</div>
              <div class="resource-value">{{ executorDetail.environmentData?.usedHeapMemoryMB || 0 }} MB</div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 趋势图表 -->
      <el-card class="detail-card" header="24小时监控趋势">
        <v-chart :option="trendChartOption" style="height: 300px;" />
      </el-card>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-container">
      <el-loading-spinner />
      <p>加载执行器详情中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="加载执行器详情失败" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Refresh, Cpu } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, LineChart, GaugeChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import { dashboardApi } from '@/services/api'
import type { ExecutorDetailVO, ApiResult } from '@/types/job'

// 注册 ECharts 组件
use([CanvasRenderer, PieChart, LineChart, GaugeChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent])

const route = useRoute()
const registerKey = route.params.registerKey as string

// 响应式数据
const loading = ref(false)
const executorDetail = ref<ExecutorDetailVO | null>(null)

// 线程池图表配置
const threadPoolChartOption = computed(() => {
  const activeCount = executorDetail.value?.activeCount || 0
  const poolSize = executorDetail.value?.poolSize || 0
  const queueSize = executorDetail.value?.queueSize || 0
  const idleCount = Math.max(0, poolSize - activeCount)
  
  return {
    title: {
      text: '线程池状态分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['活跃线程', '空闲线程', '队列任务']
    },
    series: [
      {
        name: '线程池状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: [
          { 
            value: activeCount, 
            name: '活跃线程', 
            itemStyle: { color: '#409EFF' },
            label: {
              formatter: `活跃线程: ${activeCount}`
            }
          },
          { 
            value: idleCount, 
            name: '空闲线程', 
            itemStyle: { color: '#67C23A' },
            label: {
              formatter: `空闲线程: ${idleCount}`
            }
          },
          { 
            value: queueSize, 
            name: '队列任务', 
            itemStyle: { color: '#E6A23C' },
            label: {
              formatter: `队列任务: ${queueSize}`
            }
          }
        ]
      }
    ]
  }
})

// CPU仪表盘配置
const cpuChartOption = computed(() => {
  const cpuUsage = executorDetail.value?.environmentData?.cpuUsagePercent || 0
  return {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 4,
        itemStyle: { color: '#5470c6' },
        progress: { show: true, width: 18 },
        axisLine: { lineStyle: { width: 18 } },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        pointer: { show: false },
        title: { show: false },
        detail: {
          valueAnimation: true,
          fontSize: 20,
          offsetCenter: [0, '-10%']
        },
        data: [{ value: cpuUsage, name: 'CPU' }]
      }
    ]
  }
})

// 内存仪表盘配置
const memoryChartOption = computed(() => {
  const memUsage = executorDetail.value?.environmentData?.systemMemoryUsagePercent || 0
  return {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 4,
        itemStyle: { color: '#91cc75' },
        progress: { show: true, width: 18 },
        axisLine: { lineStyle: { width: 18 } },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        pointer: { show: false },
        title: { show: false },
        detail: {
          valueAnimation: true,
          fontSize: 20,
          offsetCenter: [0, '-10%']
        },
        data: [{ value: memUsage, name: '内存' }]
      }
    ]
  }
})

// 堆内存仪表盘配置
const heapChartOption = computed(() => {
  const heapUsage = executorDetail.value?.environmentData?.heapMemoryUsagePercent || 0
  return {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 4,
        itemStyle: { color: '#fac858' },
        progress: { show: true, width: 18 },
        axisLine: { lineStyle: { width: 18 } },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: false },
        pointer: { show: false },
        title: { show: false },
        detail: {
          valueAnimation: true,
          fontSize: 20,
          offsetCenter: [0, '-10%']
        },
        data: [{ value: heapUsage, name: '堆内存' }]
      }
    ]
  }
})

// 趋势图表配置
const trendChartOption = computed(() => {
  const hourlyStats = executorDetail.value?.threadPoolStatistics?.hourlyStatistics || []
  const times = hourlyStats.map(item => `${item.hour}:00`)
  
  const memoryData = hourlyStats.map(item => item.averageMemoryUsage)
  const activeThreadData = hourlyStats.map(item => item.averageActiveThreads)
  const executorData = hourlyStats.map(item => item.executorCount)
  const taskData = hourlyStats.map(item => item.totalTasks)
  
  return {
    title: {
      text: '24小时监控趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['内存使用率(%)', '活跃线程数', '执行器数量', '任务总数'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: times,
      boundaryGap: false
    },
    yAxis: [
      {
        type: 'value',
        name: '使用率(%)',
        min: 0,
        max: 100,
        position: 'left',
        axisLabel: {
          formatter: '{value}%'
        }
      },
      {
        type: 'value',
        name: '数量',
        min: 0,
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '内存使用率(%)',
        type: 'line',
        yAxisIndex: 0,
        data: memoryData,
        itemStyle: { color: '#5470c6' },
        smooth: true,
        lineStyle: { width: 2 }
      },
      {
        name: '活跃线程数',
        type: 'line',
        yAxisIndex: 1,
        data: activeThreadData,
        itemStyle: { color: '#91cc75' },
        smooth: true,
        lineStyle: { width: 2 }
      },
      {
        name: '执行器数量',
        type: 'line',
        yAxisIndex: 1,
        data: executorData,
        itemStyle: { color: '#fac858' },
        smooth: true,
        lineStyle: { width: 2 }
      },
      {
        name: '任务总数',
        type: 'line',
        yAxisIndex: 1,
        data: taskData,
        itemStyle: { color: '#ee6666' },
        smooth: true,
        lineStyle: { width: 2 }
      }
    ]
  }
})

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

// 格式化运行时长
const formatUptime = (seconds: number) => {
  if (!seconds) return '-'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours}小时${minutes}分钟${secs}秒`
}



// 获取状态类型
const getStatusType = (status: string) => {
  switch (status?.toUpperCase()) {
    case 'ONLINE':
    case '在线':
      return 'success'
    case 'OFFLINE':
    case '离线':
      return 'info'
    default:
      return 'info'
  }
}

// 获取健康状态类型
const getHealthStatusType = (healthStatus: string) => {
  switch (healthStatus) {
    case '健康':
    case '正常':
      return 'success'
    case '警告':
      return 'warning'
    case '错误':
    case '异常':
      return 'danger'
    default:
      return 'info'
  }
}

// 加载执行器详情
const loadExecutorDetail = async () => {
  loading.value = true
  try {
    const response: ApiResult<ExecutorDetailVO> = await dashboardApi.getExecutorDetail(registerKey)
    if (response.success) {
      executorDetail.value = response.data
    } else {
      ElMessage.error('加载执行器详情失败: ' + response.message)
    }
  } catch (error) {
    console.error('加载执行器详情出错:', error)
    ElMessage.error('加载执行器详情出错')
  } finally {
    loading.value = false
  }
}

// 页面加载时执行
onMounted(() => {
  loadExecutorDetail()
})
</script>

<style scoped>
/* 页面布局 */
.fill-height {
  min-height: 100vh;
  padding: 20px;
  background: #f5f7fa;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  margin-right: 16px;
  border-radius: 0;
  border: 2px solid #e2e8f0;
  background: #ffffff;
  color: #64748b;
  transition: all 0.3s ease;
}

.back-btn:hover {
  border-color: #3b82f6;
  color: #3b82f6;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.title-icon {
  margin-right: 12px;
  font-size: 28px;
  color: #3b82f6;
}

/* 执行器详情样式 */
.executor-detail {
  max-width: 1200px;
  margin: 0 auto;
}

.detail-card {
  margin-bottom: 20px;
  border: 2px solid #e2e8f0;
  border-radius: 0;
  box-shadow: 0 2px 8px rgba(30, 58, 138, 0.1);
}

.detail-card:last-child {
  margin-bottom: 0;
}

/* 描述列表样式 */
.el-descriptions {
  border-radius: 0;
}

.el-descriptions :deep(.el-descriptions__header) {
  margin-bottom: 16px;
}

.el-descriptions :deep(.el-descriptions__title) {
  color: #1e293b;
  font-weight: 600;
}

.el-descriptions :deep(.el-descriptions__body) {
  border: 2px solid #cbd5e1;
  border-radius: 0;
}

.el-descriptions :deep(.el-descriptions__table) {
  border-collapse: collapse;
}

.el-descriptions :deep(.el-descriptions__cell) {
  border: 1px solid #e2e8f0;
  padding: 12px 16px;
  background: #ffffff;
}

.el-descriptions :deep(.el-descriptions__label) {
  background: #f1f5f9;
  color: #475569;
  font-weight: 600;
  border-right: 2px solid #cbd5e1;
}

.el-descriptions :deep(.el-descriptions__content) {
  color: #1e293b;
}

/* 按钮样式 */
.el-button {
  border-radius: 0;
  font-weight: 600;
  border: 2px solid;
  transition: all 0.3s ease;
}

.el-button--primary {
  background: #3b82f6;
  border-color: #3b82f6;
}

.el-button--primary:hover {
  background: #2563eb;
  border-color: #2563eb;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  background: #ffffff;
  border: 2px solid #e2e8f0;
  border-radius: 0;
  box-shadow: 0 2px 8px rgba(30, 58, 138, 0.1);
}

.loading-container p {
  margin-top: 16px;
  color: #64748b;
  font-size: 14px;
}

/* 内存信息样式 */
.memory-info {
  text-align: center;
  padding: 16px;
  background: #f8fafc;
  border: 2px solid #e2e8f0;
  border-radius: 0;
  margin-bottom: 16px;
}

.memory-title {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 600;
}

.memory-value {
  font-size: 18px;
  color: #1e293b;
  font-weight: bold;
}

/* 统计信息样式 */
.stat-info {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border: 2px solid #cbd5e1;
  border-radius: 8px;
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.stat-info:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-title {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 600;
}

.stat-value {
  font-size: 24px;
  color: #1e293b;
  font-weight: bold;
}

/* 资源信息样式 */
.resource-info {
  text-align: center;
  padding: 16px;
  background: #f8fafc;
  border: 2px solid #e2e8f0;
  border-radius: 0;
  margin-bottom: 16px;
}

.resource-title {
  font-size: 14px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 600;
}

.resource-value {
  font-size: 16px;
  color: #1e293b;
  font-weight: bold;
}

/* 卡片样式增强 */
.detail-card :deep(.el-card__header) {
  background: #f1f5f9;
  border-bottom: 2px solid #cbd5e1;
  padding: 16px 20px;
}

.detail-card :deep(.el-card__body) {
  padding: 20px;
}

/* 图表容器样式 */
.v-chart {
  border: 1px solid #e2e8f0;
  border-radius: 0;
  background: #ffffff;
}
</style>
